
from datetime import date, timedelta

from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from users.models import User



# 1用户总数统计
class UserTotalCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self,request):
        now_date = date.today()
        count = User.objects.all().count()
        return Response({
            'count':count,
            'date':now_date
        })

# 2日增用户统计
class UserDayCountView(APIView):
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取当日注册用户数量 date_joined 记录创建账户时间
        count = User.objects.filter(date_joined__gte=now_date).count()
        return Response({
            'count':count,
            'date':now_date
        })

# 3日活用户统计
class UserActiveCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):

        now_date=date.today()
        print(now_date)
        count = User.objects.filter(last_login__gte=now_date).count()

        return Response({
            'count':count,
            'date':now_date
        })

# 4下单用户统计
class UserOrderCountView(APIView):

    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get(self,request):

        now_date = date.today()
        count = User.objects.filter(orders__create_time__gte=now_date).count()

        return Response({
            'count':count,
            'date':now_date
        })
        pass

# 5月新增用户统计
class UserMonthCountView(APIView):
    # 指定管理员权限
    permission_classes=[IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date=date.today()
        # 获取一个月前日期
        start_date=now_date-timedelta(30)

        date_list = []
        for i in range(30):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(i)
            # 指定下一天日期
            cur_date = start_date + timedelta(i + 1)
            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(is_staff=True,date_joined__gte=index_date,date_joined__lt=cur_date).count()
            date_list.append({
                'count':count,
                'date':index_date
            })
        return Response(date_list)

# 6商品访问量统计
class GoodsDayView(APIView):
    """
        商品分类访问量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取商品分类访问量
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list=[]
        for good in goods:
            count = good.count
            # 获取关联分类对象的名字
            category = good.category.name
            data_list.append({"count":count,'category':category})
        # 返回数量
        return Response(data_list)








